<template>
  <div class="container">
    <el-breadcrumb separator="/" style="margin-bottom: 12px;">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章详情</el-breadcrumb-item>
    </el-breadcrumb>

    <template v-if="post">
      <div class="article">
        <h1 class="title">{{ post.title }}</h1>
        <div class="meta">
          <span>作者：{{ author }}</span>
          <el-divider direction="vertical" />
          <span>发布时间：{{ post.publishedAt || post.date }}</span>
          <el-divider direction="vertical" />
          <span>分类：<el-tag type="info">{{ post.category }}</el-tag></span>
        </div>
        <div class="toolbar" v-if="canEdit">
          <el-popconfirm title="确定要删除这篇文章吗？" confirm-button-text="删除" cancel-button-text="取消" confirm-button-type="danger" @confirm="doDelete">
            <template #reference>
              <el-button type="danger" size="small">删除文章</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" size="small" @click="goEdit">编辑此文</el-button>
        </div>

        <el-card shadow="never" class="content-card">
          <div class="content" v-html="post.content"></div>
          <div class="views">阅读量：{{ post.views }}</div>
        </el-card>
      </div>

      <el-card shadow="never" style="margin-top:16px;">
        <template #header>
          <div style="display:flex;align-items:center;gap:8px;">
            <strong>评论</strong>
            <el-tag type="info">{{ comments.length }}</el-tag>
          </div>
        </template>

        <div style="margin-bottom:12px;">
          <el-empty v-if="loadingComments && comments.length===0" description="加载中..." />
          <el-skeleton v-else-if="loadingComments" :rows="3" animated />
          <el-empty v-else-if="comments.length===0" description="还没有评论" />
          <el-space v-else direction="vertical" :size="12" style="width:100%;">
            <div v-for="(c, idx) in comments" :key="idx" class="comment-item">
              <div class="comment-header">
                <img :src="c.avatar" alt="" class="avatar" />
                <div class="meta">
                  <strong>{{ c.author }}</strong>
                  <span class="muted"> · {{ c.createdAt }}</span>
                </div>
              </div>
              <div class="comment-content">{{ c.content }}</div>
              <el-divider />
            </div>
          </el-space>
        </div>

        <template v-if="isUserLoggedIn">
          <el-form :model="form" @submit.prevent>
            <el-form-item label="发表评论" label-width="84px">
              <el-input
                v-model="form.content"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                placeholder="输入你的评论..."
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="!form.content.trim()" :loading="submitting" @click="submit">提交</el-button>
              <el-button @click="goHome">返回首页</el-button>
            </el-form-item>
          </el-form>
        </template>
        <template v-else>
          <div class="login-prompt">
            <el-alert
              title="需要登录才能发表评论"
              type="info"
              show-icon
              :closable="false"
            >
              <template #default>
                <p>请先登录或注册账号，然后就可以发表评论了。</p>
                <div style="margin-top: 12px;">
                  <el-button type="primary" @click="$router.push('/login')">登录</el-button>
                  <el-button @click="$router.push('/register')">注册</el-button>
                  <el-button @click="goHome">返回首页</el-button>
                </div>
              </template>
            </el-alert>
          </div>
        </template>
      </el-card>
    </template>

    <template v-else>
      <el-empty description="文章不存在或已删除">
        <el-button type="primary" @click="goHome">返回首页</el-button>
      </el-empty>
    </template>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getComments, addComment, deletePostById, fetchPostById } from '@/services/blogService'
import { getCurrentUser, isLoggedIn } from '@/services/userService'

const route = useRoute()
const router = useRouter()
const id = Number(route.params.id)
const post = ref(null)

const comments = ref([])
const loadingComments = ref(false)
const submitting = ref(false)
const form = reactive({ content: '' })

const currentUser = computed(() => getCurrentUser())
const isUserLoggedIn = computed(() => isLoggedIn())
const canEdit = computed(() => {
  const user = getCurrentUser()
  return user && post.value && post.value.authorId === user.id
})

// 获取文章作者名称
const author = computed(() => {
  if (!post.value) return 'Unknown'
  const user = getCurrentUser()
  if (user && post.value.authorId === user.id) {
    return user.username
  }
  // 如果不是当前用户的文章，显示默认作者名
  return 'Bologe'
})

onMounted(async () => {
  try {
    post.value = await fetchPostById(id)
    if (!post.value) return
    // 进入详情页即增加一次阅读量（前端临时状态，刷新不持久化）
    post.value.views = (post.value.views || 0) + 1
    await loadComments()
  } catch (error) {
    ElMessage.error('加载文章失败')
  }
})

async function loadComments() {
  loadingComments.value = true
  comments.value = await getComments(id)
  loadingComments.value = false
}

async function submit() {
  if (!isUserLoggedIn.value) {
    ElMessage.warning('请先登录才能发表评论')
    router.push('/login')
    return
  }
  
  if (!form.content.trim()) return
  
  submitting.value = true
  try {
    await addComment(id, form.content.trim())
    form.content = ''
    ElMessage.success('评论已提交')
    await loadComments()
  } catch (error) {
    ElMessage.error(error.message || '评论提交失败')
  } finally {
    submitting.value = false
  }
}

function goHome() { router.push('/') }
function goEdit() { if (post.value) router.push(`/article/${post.value.id}/edit`) }
async function doDelete() {
  if (!post.value) return
  try {
    const ok = await deletePostById(post.value.id)
    if (ok) {
      ElMessage.success('文章已删除')
      router.push('/')
    } else {
      ElMessage.error('删除失败，文章不存在')
    }
  } catch (error) {
    ElMessage.error(error.message || '删除失败')
  }
}
</script>

<style scoped>
.title { text-align: center; margin: 8px 0 6px; line-height: 1.35; }
.meta { display: flex; justify-content: center; align-items: center; gap: 8px; color: var(--color-muted); margin-bottom: 12px; flex-wrap: wrap; }
.toolbar { display: flex; justify-content: flex-end; margin-bottom: 8px; }
.content-card { overflow: hidden; }
.content { line-height: 1.8; word-break: break-word; }
.content p { margin: 0 0 12px; }
.views { margin-top: 8px; color: var(--color-muted); text-align: right; }
.comment-item .comment-header { display:flex; align-items:center; gap:8px; }
.comment-item .avatar { width:32px; height:32px; border-radius:50%; }
.comment-item .comment-content { white-space: pre-wrap; }
.login-prompt { margin-top: 16px; }
@media (max-width: 768px) {
  .content { font-size: 15px; }
}
</style>


